﻿using System;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace FlickrXplorer.Web.Utilities
{
    public class JOptions
    {
        public string TargetPanelId { get; set; }
        public string WaitPanelId { get; set; }
        /// <summary>
        /// contains the method referece or the implemenation.
        /// </summary>
        public object CallBack { get; set; }
    }

    public class JQueryForm : IDisposable
    {

        const string jString = @"return jAjaxSubmit(this, event, '{0}', '{1}', {2});";
        const string jStringOverload = @"return jAjaxSubmit(this, event, '{0}','{1}');";

        private readonly HttpResponseBase responseBase = null;

        public JQueryForm(HtmlHelper helper, string url, string method, JOptions options, object htmlAttributes)
        {
            if (string.IsNullOrEmpty(options.TargetPanelId))
            {
                throw new Exception("Must provide a valid target panel");
            }

            TagBuilder builder = new TagBuilder("form");

            builder.MergeAttribute("action", url);
            builder.MergeAttribute("method", method);
            builder.MergeAttributes<string, object>(new RouteValueDictionary(htmlAttributes));

            if (options.CallBack == null)
            {
                builder.MergeAttribute("onsubmit",
                                       string.Format(jStringOverload, options.WaitPanelId, options.TargetPanelId));
            }
            else
            {
                builder.MergeAttribute("onsubmit",
                                       string.Format(jString, options.WaitPanelId, options.TargetPanelId, options.CallBack));
            }

            responseBase = helper.ViewContext.HttpContext.Response;
            responseBase.Write(builder.ToString(TagRenderMode.StartTag));
        }

        #region IDisposable Members

        public void Dispose()
        {
            responseBase.Write("</form>");
        }

        #endregion
    }
}
